<template>
	<div>
		<div class="box">
			<div class="title">保险</div>
			<div class="">
				<div class="">
					<!-- <InsuranceInfoTable -->
					<!-- v-if="details.carSourceType == '3'" -->
					<!-- ref="InsuranceInfoTable" -->
					<!-- v-model="formData" -->
					<!-- :state="state" -->
					<!-- :type="type" -->
					<!-- :index="index"></InsuranceInfoTable> -->
					<!-- v-if=" -->
					<!-- details.carSourceType == '1' || -->
					<!-- details.carSourceType == '2' || -->
					<!-- showInsuranceList -->
					<!-- " -->
					<InsuranceInfo
						style="margin-top: 30px"
						ref="InsuranceInfo"
						v-model="formData"
						:state="state"
						:type="type"
						@initDetaultInsuranceList="initDetaultInsuranceList"
						:index="index"></InsuranceInfo>
					<!-- v-if="showInsuranceList" -->
					<div class="content_table">
						<div class="content_table-title">商业险险种</div>
						<div :key="formData.insuranceStandardType">
							<el-form
								:model="formData"
								ref="form"
								label-width="5px"
								:inline="false"
								size="normal"
								:hide-required-asterisk="true">
								<el-table
									ref="multipleTable"
									:data="formData.insuranceList"
									tooltip-effect="dark"
									style="width: 100%"
									:header-cell-class-name="setHeaderCellName">
									<el-table-column
										v-if="state == 'readonly'"
										width="100px"
										align="center">
										<template slot-scope="scope">
											<i
												class="el-icon-check"
												v-if="
													!(
														scope.row
															.operationType ==
															'2' &&
														scope.row
															.selectedType == '2'
													)
												"></i>
										</template>
									</el-table-column>
									<el-table-column
										label="操作"
										width="100"
										align="center"
										v-if="state == 'write'">
										<template slot-scope="scope">
											<el-checkbox
												v-if="
													scope.row.operationType ==
													'2'
												"
												true-label="1"
												false-label="2"
												v-model="scope.row.selectedType"
												:disabled="
													formData.insuranceStandardType !==
													'4'
												"></el-checkbox>
											<div v-else>
												<el-button
													type="text"
													@click="
														remove(
															scope.$index,
															scope.row,
															formData.insuranceList,
														)
													">
													删除
												</el-button>
											</div>
										</template>
									</el-table-column>

									<TableCloumn
										v-for="(item, index) in tableCloumns"
										:cellOptions="item"
										dataName="insuranceList"
										:state="state"></TableCloumn>
								</el-table>
							</el-form>
							<div
								class="btn"
								@click="add(formData.insuranceList)"
								v-if="state == 'write'">
								<i class="el-icon-plus"></i>
								<span>增加其他商业险种</span>
							</div>
						</div>

						<!-- <div v-if="details.carSourceType == '2'"> -->
						<!-- <FormItems -->
						<!-- ref="form1" -->
						<!-- v-model="formData" -->
						<!-- :form="formList" -->
						<!-- :state="state"></FormItems> -->
						<!-- </div> -->
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import FormItems from '@/views/finance/manage/formItems/index.vue';
	import FormItem from '@/views/finance/reimburs/formItem/index.vue';
	import TableCloumn from '@/views/finance/manage/tableColumn/index.vue';
	import InsuranceInfo from '../carInfoChunk/insuranceInfo';
	import InsuranceInfoTable from '../carInfoChunk/insuranceInfoTable';
	import * as apis from '@/api/quota/forecast/edit/api.js';
	export default {
		components: {
			TableCloumn,
			FormItems,
			FormItem,
			InsuranceInfo,
			InsuranceInfoTable,
		},
		dicts: ['quota_maintenance_meal'],
		props: {
			value: {
				required: false,
			},
			state: {
				required: false,
			},
			type: {
				required: false,
			},
			planDicts: {
				required: false,
			},
			citylist: {
				required: false,
			},
		},
		inject: ['details_forecast'],
		provide() {
			return {
				_planDicts: () => this.planDicts,
				// _cityList: () => this.cityList,
				// _insuranceList: () => this.insuranceList,
				// _currentFormData: () => this.formData,
				// _refittedList: () => this.refittedList,
				_index: () => 0,
			};
		},
		watch: {
			showInsuranceList(val, oldVal) {
				if (val == false) {
					// this.$set(this.formData, 'insuranceList', []);
				}
				if (oldVal == false && val == true) {
					// this.formData.insuranceStandardType = "4";
					// this.initDetaultInsuranceList("4");
				}
			},
			insuranceCompulsoryDiffAmount_dif: {
				handler(val) {
					this.formData.insuranceCompulsoryDiffAmount = val;
				},
				immediate: true,
			},
			insuranceCarvesselDiffAmount_dif: {
				handler(val) {
					this.formData.insuranceCarvesselDiffAmount = val;
				},
				immediate: true,
			},
			insuranceCommercialDiffAmount_dif: {
				handler(val) {
					this.formData.insuranceCommercialDiffAmount = val;
				},
				immediate: true,
			},
			'formData.insuranceStandardType': {
				handler(val) {
					this.initDetaultInsuranceList(val, true);
				},
				// immediate: true,
			},
		},
		data() {
			return {
				dicts: {
					insuranceBuyModeType12: [
						{
							value: '1',
							label: '我司购买',
						},
						{
							value: '2',
							label: '店保',
						},
					],
					insuranceBuyModeType3: [
						{
							value: '3',
							label: '客户自购',
						},
					],
					productA: [],
					productB: [],
					productC: [],
				},
			};
		},
		computed: {
			index() {
				return 0;
			},
			formData: {
				get() {
					return this.useVModel.call(this);
				},
				set(val) {
					this.$emit('input', val);
				},
			},
			details() {
				return this.details_forecast();
			},
			showTable() {
				let result = false;
				let list = this.formData?.insuranceConfList ?? [];
				for (let index = 0; index < list.length; index++) {
					const element = list[index];
					if (
						element.purchaserType == '2' ||
						element.purchaserType == '3'
					) {
						result = true;
						break;
					}
				}
				return result;
			},
			tableCloumns() {
				return [
					{
						label: '险种',
						prop: 'insuranceItemNameVal',
						type: (row, index) => {
							if (
								this.formData.insuranceList[index]
									?.operationType == '2'
							) {
								return 'text';
							} else {
								return 'input';
							}
						},
						fitContent: false,
						rules: true,
					},

					// {
					//     label: "不计免赔",
					//     prop: "irrespectiveType",
					//     type: "checkbox",
					//     prototype: {
					//         trueLabel: "1",
					//         falseLabel: "2",
					//     },
					// },
					{
						label: '保额',
						prop: 'sumInsuredVal',
						type: (row, index) => {
							return 'input_number';
						},
						tag: 'price',
						array: true,
						selectList: (row, index) => {
							let arr = [];
							try {
								arr = JSON.parse(
									this.formData.insuranceList[index]
										?.coverageAmountList,
								);
							} catch (error) {}
							return arr;
						},
						fitContent: false,
						show: this.type == 'preview',
					},
					{
						label: '保额',
						prop: 'sumInsuredVal',
						show: this.type !== 'preview',
						type: (row, index) => {
							if (
								this.formData.insuranceList[index]
									?.operationType !== '2'
							) {
								return 'input_number';
							}
							if (
								this.formData.insuranceList[index]
									?.isCoverageAmount *
									1 ==
								1
							) {
								return 'select';
							} else {
								return 'text';
							}
						},
						format: (row, index) => {
							let arr = [];
							try {
								arr = JSON.parse(row.coverageAmountList);
							} catch (error) {}

							if (
								this.Empty(row.sumInsuredVal) &&
								this.Empty(arr) &&
								row.operationType == '2'
							) {
								if (row.selectedType == '1') {
									return '加入';
								} else {
									return '未加入';
								}
							}
							return row.sumInsuredVal;
						},
						array: true,
						selectList: (row, index) => {
							let arr = [];
							try {
								arr = JSON.parse(
									this.formData.insuranceList[index]
										?.coverageAmountList,
								);
							} catch (error) {}
							return arr;
						},
						fitContent: false,
						state: (row, index) => {
							return this.state == 'readonly'
								? 'readonly'
								: this.formData.insuranceStandardType == '4' ||
								  row?.operationType == '1'
								? 'write'
								: 'disabled';
						},

						rules: (row, index) => {
							if (
								this.formData.insuranceList[index]
									?.selectedType == '2'
							) {
								return false;
							}
							return true;
						},
					},
				];
			},
			showInsuranceList() {
				return (
					this.details.carSourceType !== '3' ||
					(this.details.carSourceType == '3' && this.showTable)
				);
			},
			formList() {
				return [
					// {
					//     label: "上牌城市",
					//     placeholder: "请输入上牌城市",
					//     type: "select",
					//     selectList: this.cityList,
					//     selectLabel: "regionName",
					//     selectValue: "regionId",
					//     prop: "carLicenseCityKey",
					//     rules: [
					//         {
					//             required: true,
					//             message: "请选择上牌城市",
					//             trigger: "change",
					//         },
					//     ],
					//     event: {
					//         type: "change",
					//         cb: (row) => {
					//             let item = this.cityList.find(
					//                 (e) => e.regionId == row.carLicenseCityKey
					//             );
					//             this.formData.carLicenseCityVal = item.regionName;
					//         },
					//     },
					// },
					{
						label: '上牌城市',
						type: 'select',
						selectList: this.deptList.company,
						selectLabel: 'deptName',
						selectValue: 'deptId',
						prop: 'carLicenseCityKey',
						rules: true,
						event: {
							type: 'change',
							cb: row => {
								let item = this.deptList.company.find(
									e => e.deptId == row.carLicenseCityKey,
								);
								if (item) {
									let regionId = item.regionId.split('/');
									this.formData.carCalcCityKey =
										regionId?.[1];
									this.formData.carLicenseCityVal =
										item.deptName;
								}
							},
						},
					},
					{
						label: '开发城市',
						type: 'select',
						selectList: this.deptList.company,
						selectLabel: 'deptName',
						selectValue: 'deptId',
						prop: 'carAffiliationKey',
						rules: true,
						event: {
							type: 'change',
							cb: row => {
								let item = this.deptList.company.find(
									e => e.deptId == row.carAffiliationKey,
								);
								this.formData.carAffiliationVal =
									item?.deptName;
							},
						},
					},
					{
						label: '运营城市',
						placeholder: '请输入运营城市',
						type: 'input',
						prop: 'carOperateCityVal',
						rules: true,
					},
					// {
					//     label: "上牌费（台）",
					//     placeholder: "请输入金额",
					//     type: "input_number",
					//     prop: "carLicensePrice",
					//     show:
					//         this.details.carSourceType == "1" &&
					//         this.details.outsourcingType == "1",
					// },
					// {
					//     label: "限牌城市牌照费（台）",
					//     placeholder: "请输入金额",
					//     type: "input_number",
					//     prop: "carLicenseCityPrice",
					//     show:
					//         this.details.carSourceType == "1" &&
					//         this.details.outsourcingType == "1",
					// },
					// {
					//     label: "购置税（台）",
					//     placeholder: "请输入金额",
					//     type: "input_number",
					//     prop: "carPurchaseTax",
					//     show:
					//         this.details.carSourceType == "1" &&
					//         this.details.outsourcingType == "1",
					// },
				];
			},
		},
		async created() {
			await this.getProductList();
			this.initDetaultInsuranceList(this.formData.insuranceStandardType);
		},
		beforeDestroy() {
			// if (this.notEmpty(this.details?.productList?.[this.index])) {
			// 	this.$refs.form?.form_resetFields?.();
			// }
		},
		mounted() {},
		methods: {
			// getFilterInsuranceList(type) {
			// 	let dictList = [];
			// 	switch (type) {
			// 		case '1':
			// 			// dictList = await this._getDicts("pro_duct_in_sur_ance_a");
			// 			dictList = this.dicts.productA;
			// 			break;
			// 		case '2':
			// 			// dictList = this.dict.type.pro_duct_in_sur_ance_b;
			// 			dictList = this.dicts.productB;
			// 			break;
			// 		case '3':
			// 			dictList = this.dicts.productC;
			// 			// dictList = this.dict.type.pro_duct_in_sur_ance_c;
			// 			break;
			// 	}
			// 	let list = this.insuranceList.map(item => {
			// 		let child = dictList.find(e => {
			// 			return (
			// 				e.dictLabel?.trim() ==
			// 				item.insuranceItemName?.trim()
			// 			);
			// 		});
			// 		let obj = {
			// 			...item,
			// 		};
			// 		if (child?.remark) {
			// 			let price = child.remark?.trim() * 1;
			// 			obj.sumInsuredVal = price;
			// 		}

			// 		if (this.notEmpty(child)) {
			// 			return obj;
			// 		}
			// 	});
			// 	return list.filter(e => this.notEmpty(e));
			// },
			// 获取报价替代车列表
			initDetaultInsuranceList(type, clear) {
				let insuranceArr = [],
					insuranceList = this._.cloneDeep(
						this.formData.insuranceList,
					);
				if (type == '') {
					return;
				}
				this.$set(this.formData, 'insuranceList', []);
				let list = [];
				if (type == '4') {
					list = this._.cloneDeep(this.insuranceList);
				} else {
					list = this.getFilterInsuranceList(type);
				}
				// 获取套餐内险种
				list?.map(item => {
					let child = insuranceList?.find(e => {
						return e.insuranceItemNameVal == item.insuranceItemName;
					});
					if (!child) child = {};

					insuranceArr.push({
						...child,
						insuranceItemNameKey: item.insuranceItemId,
						insuranceItemNameVal: item.insuranceItemName,
						isCoverageAmount: item.isCoverageAmount?.toString(),
						coverageAmountList: JSON.stringify(
							item.coverageAmountList,
						),
						selectedType: child.selectedType ?? '1',
						operationType: '2',
						irrespectiveType: '1',
						sumInsuredVal:
							type == '4'
								? child.sumInsuredVal
								: item.sumInsuredVal?.toString(),
					});
				});
				//  获取自定义险种
				if (!clear) {
					insuranceList?.map(item => {
						if (item.operationType == '1') {
							insuranceArr.push(item);
						}
					});
				}
				this.formData.insuranceList = insuranceArr;
			},

			setHeaderCellName({ columnIndex }) {
				if (this.state == 'readonly') {
					return '';
				}
				if (columnIndex !== 0 && columnIndex !== undefined) {
					return 'ruleHeaderCell';
				}
			}, // 删除 险种
			remove(index, row, list) {
				this.$confirm(
					`此操作将删除 ${
						row?.insuranceItemNameVal
							? row?.insuranceItemNameVal + '险种'
							: '该险种'
					}, 是否继续?`,
					'提示',
					{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					},
				)
					.then(() => {
						list.splice(index, 1);
					})
					.catch(() => {});
			},
			// 新增 险种
			add(list) {
				list.push({
					insuranceItemNameKey: '',
					insuranceItemNameVal: '',
					selectedType: '1',
					operationType: '1',
					irrespectiveType: '1',
					sumInsuredVal: undefined,
					isCoverageAmount: '1',
					coverageAmountList: JSON.stringify(
						this.defaultsumInsurList,
					),
					tag: true,
				});
			},
			initDetaultInsuranceList(type, clear) {
				let insuranceArr = [],
					insuranceList = this._.cloneDeep(
						this.formData.insuranceList,
					);
				if (type == '') {
					return;
				}
				this.$set(this.formData, 'insuranceList', []);
				let list = [];
				if (type == '4') {
					list = this._.cloneDeep(this.insuranceList);
				} else {
					list = this.getFilterInsuranceList(type);
				}
				// 获取套餐内险种
				list?.map(item => {
					let child = insuranceList?.find(e => {
						return e.insuranceItemNameVal == item.insuranceItemName;
					});
					if (!child) child = {};
					// insuranceArr.push({
					//     ...child,
					//     selectedType: "1",
					//     operationType: "2",
					//     irrespectiveType: "1",
					//     coverageAmountList: JSON.stringify(item.coverageAmountList),
					// });
					insuranceArr.push({
						...child,
						insuranceItemNameKey: item.insuranceItemId,
						insuranceItemNameVal: item.insuranceItemName,
						isCoverageAmount: item.isCoverageAmount?.toString(),
						coverageAmountList: JSON.stringify(
							item.coverageAmountList,
						),
						selectedType: child.selectedType ?? '1',
						operationType: '2',
						irrespectiveType: '1',
						sumInsuredVal:
							type == '4'
								? child.sumInsuredVal
								: item.sumInsuredVal?.toString(),
					});
				});
				//  获取自定义险种
				if (!clear) {
					insuranceList?.map(item => {
						if (item.operationType == '1') {
							insuranceArr.push(item);
						}
					});
				}
				this.formData.insuranceList = insuranceArr;
			},
			async getProductList() {
				return new Promise(resolve => {
					Promise.all([
						this._getDicts('pro_duct_in_sur_ance_a'),
						this._getDicts('pro_duct_in_sur_ance_b'),
						this._getDicts('pro_duct_in_sur_ance_c'),
						this.getInsuranceList(),
					])
						.then(values => {
							this.dicts.productA = values?.[0];
							this.dicts.productB = values?.[1];
							this.dicts.productC = values?.[2];
						})
						.finally(() => {
							resolve();
						});
				});
			},
			// 商业险险种
			async getInsuranceList() {
				return new Promise(resolve => {
					apis.Insurance({})
						.then(res => {
							if (res.code == 200) {
								this.insuranceList = res.data;
							}
						})
						.finally(() => {
							resolve();
						});
				});
			},
			getFilterInsuranceList(type) {
				let dictList = [];
				switch (type) {
					case '1':
						// dictList = await this._getDicts("pro_duct_in_sur_ance_a");
						dictList = this.dicts.productA;
						break;
					case '2':
						// dictList = this.dict.type.pro_duct_in_sur_ance_b;
						dictList = this.dicts.productB;
						break;
					case '3':
						dictList = this.dicts.productC;
						// dictList = this.dict.type.pro_duct_in_sur_ance_c;
						break;
				}
				let list = this.insuranceList?.map(item => {
					let child = dictList.find(e => {
						return (
							e.dictLabel?.trim() ==
							item.insuranceItemName?.trim()
						);
					});
					let obj = {
						...item,
					};
					if (child?.remark) {
						let price = child.remark?.trim() * 1;
						obj.sumInsuredVal = price;
					}

					if (this.notEmpty(child)) {
						return obj;
					}
				});
				return list?.filter(e => this.notEmpty(e));
			},
			// 加装
			getDecorationList() {
				if (!this.formData?.plan?.carSeating) {
					this.refittedList = [];
					this.$set(this.formData, 'attachedDecorationList', []);
					return;
				}
				let params = {
					seat: this.formData.plan?.carSeating,
				};
				apis.Decoration(params).then(res => {
					if (res.code == 200) {
						this.refittedList = res.data;
						// this.initDetaultRefittedList();
					}
				});
			},
			initDetaultRefittedList() {
				this.formData.attachedDecorationList = [];
				this.refittedList?.map(item => {
					this.formData.attachedDecorationList.push({
						decorationVal: item.decorationName,
						decorationPrice: item.decorationFee,
						decorationCount: 0,
						operationType: '2',
						selectedType: '2',
						remark: '',
					});
				});
			},
			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (
							Object.prototype.toString.call(ref) ==
							'[object Array]'
						) {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(
										ref,
										'form_validate',
									);
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(
									ref,
									'form_validate',
								);
								result = result && rf;
							}
						}
					}

					resolve(result);
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.box {
		margin: 20px;
		padding: 20px;
		border-radius: 8px;
		background-color: #fff;
		box-shadow: 0px 1px 3px 1px rgba(0, 28, 54, 0.11);
		.title {
			font-size: 16px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			color: #333333;
			line-height: 22px;
			padding-bottom: 15px;
			border-bottom: 1px solid #e9e9e9;
		}
	}
	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 48px;
		background: #ffffff;
		border-radius: 4px;
		border: 1px solid #dadada;
		color: #1890ff;
		margin-top: 15px;
		font-size: 14px;
		cursor: pointer;
	}
	.content_table {
		background-color: #f7fbff;
		border-radius: 4px;
		padding: 16px;
		margin-top: 15px;
		.content_table-title {
			font-size: 14px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			color: #464646;
			line-height: 22px;
			padding-bottom: 10px;
		}
	}
</style>
